﻿using System;
using System.Web;
using Jobping.StickyBeak.Config;

namespace Jobping.StickyBeak.HttpModule
{
    /// <summary>
    ///     An HttpModule to call the WebRequestLogger.Log method on every request.
    /// </summary>
    public class StickBeakModule : IHttpModule
    {
		private static StickyBeakConfiguration config = StickyBeakConfiguration.Current();

		public WebRequestBuilder builder = new WebRequestBuilder(
			config.IgnoreHeaderKey,
			config.IgnoreQueryStringKey,
			config.IgnoreFormKey,
			config.IgnoreCookie,
			config.IgnoreSessionKey
			);

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.PostAcquireRequestState += new EventHandler(RecordRequest);    
        }

		void RecordRequest(object sender, EventArgs e)
        {
			if (!config.Enabled)
				return;

			if(config.IgnoreUrl(HttpContext.Current.Request.Url.AbsolutePath))
				return;

			var context = new HttpContextWrapper(HttpContext.Current);
			var webRequest = builder.Build(context);

			ILogRepository repository = config.GetRepository();
			repository.Record(webRequest);
        }
    }
}
